﻿using Microsoft.Win32;
using SimpleConnection_UDP_WIN.data;
using SimpleConnection_UDP_WIN.extension_class.form_ui;
using SimpleConnection_UDP_WIN.extension_class.hidden;
using SimpleConnection_UDP_WIN.extension_class.utils;
using SimpleConnection_UDP_WIN.interface_class;
using SimpleConnection_UDP_WIN.ui;
using SimpleConnection_UDP_WIN.utils;
using System;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using UDPshutdown1.utils;
using WindowsImageCompressionApp.utils;

namespace SimpleConnection_UDP_WIN
{
    public partial class Form1 : Form
    {

        private UdpClient udpClient;
        public static Form1 Instance { get; private set; }

        public Form1()
        {
            InitializeComponent(); 
            Instance = this;
        }


        private void button3_Click(object sender, EventArgs e)
        {
            DBUtil.openLink(Constant.LOCALSEND_URL);

        }

        private void button2_Click(object sender, EventArgs e)
        {
            DBUtil.openLink(Constant.SC_UDP_URL);
        }

        //进入窗口执行的
        private void Form1_Load(object sender, EventArgs e)
        {

            Console.WriteLine("---------------程序启动！！！！--------------------");

            try
            {
                // 创建一个UdpClient对象，并绑定到本地IP地址和端口号
                udpClient = new UdpClient(new IPEndPoint(IPAddress.Any, 8870));
                // 开始异步接收UDP数据
                udpClient.BeginReceive(ReceiveCallback, null);
               
                
               
                //获取电脑IP
                label1.Text = $"IP：{NetUtil.getLocalIp()} - PORT：8870 - {(DBUtil.currentIsAdmin()?"拥有管理员权限":"非管理员权限")}";
            }
            catch (Exception ex)
            {
                MessageBox.Show($"程序异常：{ex.Message}","程序异常");
                DBUtil.killProcessByName(DBUtil.getCurrentProcessName());
            }

            //扫描所有插件
            scanAllPluginClass();
            //读取设置
            processingSettingsReading();

        }

        /// <summary>
        /// 读取配置项 注册表
        /// </summary>
        private void processingSettingsReading()
        {

            Console.WriteLine($"自启动路径：{AppAutoStarter.LnkFilePath}");

            if (File.Exists(AppAutoStarter.LnkFilePath))
            {
                //存在自启动文件
                checkBox1.Checked = true;
            }
            else
            {
                checkBox1.Checked = false;
            }


            // 读取注册表项的值
            string password = RegistryUtils.getString("password", "123456");

            if (!string.IsNullOrEmpty(password))
            {
                checkBox2.Checked = true;
                textBox1.Text = password;
            }

            // 读取注册表项的值
            int auto_hidden = RegistryUtils.getInt("auto_hidden", 0);
            Console.WriteLine($"自动隐藏时间：{auto_hidden}");

            if (auto_hidden != 0)
            {
                checkBox3.Checked = true;
                textBox2.Text = auto_hidden.ToString();
            }

            checkBox2.Checked = RegistryUtils.getInt("check_password", 1) == 1;
            checkBox3.Checked = RegistryUtils.getInt("check_auto_hidden", 0) == 1;
            checkBox4.Checked = RegistryUtils.getInt("playSound", 0) == 1;


            if (RegistryUtils.getInt("check_auto_hidden", 0) == 1 && auto_hidden !=0)
            {

                //新线程
                new Thread(new ThreadStart(delegate ()
                {
                    //延时
                    Thread.Sleep(millisecondsTimeout: auto_hidden); // 延时3秒
                    if (InvokeRequired)
                    {
                        Invoke(new Action(() =>
                        {
                            this.Hide();
                        })); // 在主线程中操作UI
                    }
                    else
                    {
                        this.Hide();
                    }

                })).Start();

            }


        }


        private void scanAllPluginClass()
        {
            // 获取当前程序集中所有类型
            Type[] types = Assembly.GetExecutingAssembly().GetTypes();

            // 使用LINQ查询获取继承自AClass接口的类
            var derivedClasses = types.Where(t => typeof(PluginBaseInfoInterface).IsAssignableFrom(t) && t.IsClass);

            // 输出每个类中的Version属性值
            foreach (var derivedClass in derivedClasses)
            {
                PropertyInfo nameProperty = derivedClass.GetProperty("Name");
                PropertyInfo versionProperty = derivedClass.GetProperty("Version");
                
                if (versionProperty != null)
                {
                    // 添加列表项
                    ListViewItem item1 = new ListViewItem((string)nameProperty.GetValue(Activator.CreateInstance(derivedClass))); // 第一列的值
                    Console.WriteLine($"加载插件类：{derivedClass.FullName}");
                    item1.SubItems.Add(derivedClass.Name); // 添加其他列的值
                    item1.SubItems.Add((string)versionProperty.GetValue(Activator.CreateInstance(derivedClass))); // 添加其他列的值
                    listView1.Items.Add(item1);

                }
            }
            label4.Text = $"插件数量：{derivedClasses.Count()}个";
        }

        private void ReceiveCallback(IAsyncResult ar)
        {
            // 接收UDP数据
            IPEndPoint remoteEP = null;
            try
            {
                byte[] data = udpClient.EndReceive(ar, ref remoteEP);

                // 在UI线程中处理接收到的数据
                BeginInvoke(new Action(() =>
                {
                    // 处理接收到的数据
                    string message = System.Text.Encoding.UTF8.GetString(data);
                    HandleReceiveMessage(message, remoteEP.Address.ToString(), remoteEP.Port);

                    try
                    {
                        // 继续异步接收UDP数据
                        udpClient.BeginReceive(ReceiveCallback, null);
                    }
                    catch (Exception)
                    {
                    }

                }));
            }
            catch (Exception) { }

        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {

            Hide(); // 隐藏窗体
            e.Cancel = true; // 取消关闭操作
            
        }

        /// <summary>
        /// 接收消息 处理
        /// </summary>
        /// <param name="message"></param>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        public void HandleReceiveMessage(string message, string ip, int port)
        {
            try
            {

                listboxAddMessage($"{ip}-{port}:{message}");
                HandlePluginClass(message, ip, port);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
        }



        public void listboxAddMessage(string text)
        {

            listBox1.Items.Add(text);
            listBox1.TopIndex = listBox1.Items.Count - 1;
        }

        /// <summary>
        /// 处理完 传给各个插件，在此处加载插件
        /// </summary>
        /// <param name="message"></param>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        public void HandlePluginClass(string message, string ip, int port)
        {
            Console.WriteLine($"处理交给{MessageParsingClass.getProtocol(message)}");

            switch (MessageParsingClass.getProtocol(message))
            {
                case KeyAndMouseCtrl.Protocol:
                    new KeyAndMouseCtrl(message, ip, port).exec();
                    break;
                case OpenLinkClass.Protocol:
                    new OpenLinkClass(message, ip, port).exec();
                    break;
                case NetworkMediaPlayClass.Protocol:
                    new NetworkMediaPlayClass(message, ip, port).exec();
                    break;
                case ToastClass.Protocol:
                    new ToastClass(message, ip, port).exec();
                    break;
                case ShowOrHideClass.Protocol:
                    new ShowOrHideClass(message, ip, port).exec();
                    break;
                case ShutdownClass.Protocol:
                    new ShutdownClass(message, ip, port).exec();
                    break;
                case ShowDialogClass.Protocol:
                    new ShowDialogClass(message, ip, port).exec();
                    break;
                case ExitClass.Protocol:
                    new ExitClass(message, ip, port).exec();
                    break;
                default:
                    listboxAddMessage("未匹配到对应插件类");
                    break;
            }
        }



        private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
            {
                string firstColumnValue = listView1.SelectedItems[0].SubItems[1].Text;

                string targetClassName = firstColumnValue;

                Assembly assembly = Assembly.GetExecutingAssembly(); // 获取当前程序集
                Type[] types = assembly.GetTypes(); // 获取程序集中的所有类型

                foreach (Type type in types)
                {
                    if (type.Name == targetClassName)
                    {
                        PluginBaseInfoInterface instance = (PluginBaseInfoInterface)Activator.CreateInstance(type); // 使用Type对象创建对象实例
                        MessageBox.Show($"名称：{instance.Name}\n版本：{instance.Version}\n描述：{instance.Describe}\n使用方法：{(instance.Help.Equals("-")?"请查看详细功能介绍": instance.Help)}", "插件信息", MessageBoxButtons.OK, MessageBoxIcon.Information);

                        return;
                    }
                }



            }
        }


        /// <summary>
        /// 重写这个方法 限制输入类型
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            string text = textBox1.Text;
            string filteredText = new string(text.Where(char.IsLetterOrDigit).ToArray()); // 只保留数字字符
            if (text != filteredText)
            {
                textBox1.Text = filteredText;
                textBox1.SelectionStart = filteredText.Length; // 设置光标位置
            }
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {
            string text = textBox2.Text;
            string filteredText = new string(text.Where(char.IsDigit).ToArray()); // 只保留数字字符
            if (text != filteredText)
            {
                textBox2.Text = filteredText;
                textBox2.SelectionStart = filteredText.Length; // 设置光标位置
            }
        }

        /// <summary>
        /// 保存按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
           
            if (!string.IsNullOrEmpty(textBox1.Text))
            {
                RegistryUtils.setString("password", textBox1.Text);
            }

            if (!string.IsNullOrEmpty(textBox2.Text))
            {
                if (int.Parse(textBox2.Text) >= 3000)
                {
                RegistryUtils.setInt("auto_hidden", int.Parse(textBox2.Text));
                }
                else
                {
                    MessageBox.Show("延时必须大于3000");
                }
            }

            RegistryUtils.setInt("check_password", checkBox2.Checked ? 1 : 0);
            RegistryUtils.setInt("check_auto_hidden", checkBox3.Checked ? 1 : 0);

        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
     
            if (checkBox1.Checked)
            {
                AppAutoStarter.EnableAutoStart();
            }
            else
            {
                AppAutoStarter.DisableAutoStart();
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            // 关闭UdpClient
            udpClient.Close();
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            DBUtil.openLink("https://gitee.com/dabai2017/simple-connection-udp-win/blob/master/%E7%9B%AE%E5%89%8D%E6%8B%A5%E6%9C%89%E7%9A%84%E6%8F%92%E4%BB%B6%E7%B1%BB%E4%BB%8B%E7%BB%8D.MD");
        }

        private void menuItem4_Click(object sender, EventArgs e)
        {
            Environment.Exit(0);
        }

        private void checkBox4_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox4.Checked)
            {
                RegistryUtils.setInt("playSound", 1);
            }
            else
            {
                RegistryUtils.setInt("playSound", 0);
            }
        }

        private void menuItem2_Click(object sender, EventArgs e)
        {
            new JsonEditForm().Show();
        }
    }
}
